﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebCommon;

namespace SharedModule
{
    public class MockSocketServerHub
    {

        public static MockSocketServer createServer(string serverName)
        {
            List<string> listKey = MockSocketServerHub.GetOrCreateServerList();
            if (listKey.Contains(serverName))
            {
                LogUtility.Log.Warn("Dupliacated server, just return the server which stored in cache.");
                return MockSocketServerHub.GetServer(serverName);
            }
            else
            {
                MockSocketServer instance = new MockSocketServer(MockConst.SERVER_PORT);
                listKey.Add(serverName);
                CacheUtility.SetCache(MockConst.SERVER_LIST, listKey);
                CacheUtility.SetCache(serverName, instance);
                return instance;
            }
        }

        public static List<MockSocketServer> GetServerList()
        {
            List<string> listKey = MockSocketServerHub.GetOrCreateServerList();
            List<MockSocketServer> list = new List<MockSocketServer>();
            foreach (var key in listKey)
            {
                list.Add(CacheUtility.GetCache(key) as MockSocketServer);
            }
            return list;
        }

        public static MockSocketServer GetServer(string key)
        {
            return CacheUtility.GetCache(key) as MockSocketServer;
        }

        private static List<string> GetOrCreateServerList()
        {
            List<string> listKey = CacheUtility.GetCache(MockConst.SERVER_LIST) as List<string>;
            if (listKey == null)
            {
                CacheUtility.SetCache(MockConst.SERVER_LIST, new List<string>());
                return CacheUtility.GetCache(MockConst.SERVER_LIST) as List<string>;
            }
            return listKey;
        }
    }
}
